// pages/match/match.js
var match = require('../../utils/match');
Page({
  tijiao(){
    var that = this;
    var matchid = this.data.matchid;
    var index = this.data.category;
    var userid = this.data.userid;
    var username = this.data.username;
    var time = new Date();
    var image = null;
    wx.chooseMedia({
      count: 1,
      success(res) {
          console.log(res.tempFiles)
          var po = res.tempFiles[0].tempFilePath.lastIndexOf(".")
          var ext = res.tempFiles[0].tempFilePath.slice(po)
          wx.cloud.uploadFile({
              cloudPath: matchid+index+userid + ext,
              filePath: res.tempFiles[0].tempFilePath,
              success(res) {
                  console.log(res.fileID);
                  image = res.fileID;
                  that.setData({
                    currentImage:image
                  });
                  var database = wx.cloud.database();
                  database.collection("tb_item").add({
                    data:{
                      matchid:matchid,
                      index:index,
                      userid:userid,
                      username:username,
                      time:time,
                      image:image
                    }
                  }).then((s)=>{
                    if(s)wx.showToast({
                      title: '提交图片成功',
                    })
                    //判断是否已经完成整场比赛
                     database.collection("tb_item").where({
                         matchid:that.data.matchid,
                         userid:that.data.userid
                     }).get().then((b)=>{
                         //判断用户完成的当前比赛的分项数量是否等于比赛中的场景数量
                          if(b.data.length == that.data.imageList.length){
                              var matchid = that.data.matchid;
                              var matchname = that.data.matchname;
                              var userid = that.data.userid;
                              var username = that.data.username;
                              //寻找当前用户的名次
                              database.collection("tb_final").where({
                                  matchid:matchid,
                                  userid:userid
                              }).get().then((c)=>{
                                  var len = c.data.length;
                                  var mingci = len+1;
                                  //获取比赛的结束时间
                                  var endTime = new Date();
                                  //获取比赛的开始时间
                                  database.collection("tb_match").where({
                                      _id:matchid
                                  }).get().then((d)=>{
                                      var beginTime = d.data[0].beginTime;
                                      //比赛的时间间距
                                      var shijiancha = endTime.getTime()-beginTime.getTime();
                                      var hours = Math.floor(shijiancha/(1000*60*60));
                                      var min = Math.floor(shijiancha%(1000*60*60)/60000);
                                      var sec = Math.floor(shijiancha%60000/1000);
                                      var haoshi = hours+"小时"+min+"分钟"+sec+"秒钟";
                                      database.collection("tb_final").add({
                                          data:{
                                              matchid:matchid,
                                              matchname:matchname,
                                              userid:userid,
                                              username:username,
                                              mingci:"第"+mingci+"名",
                                              shijiancha:shijiancha,
                                              haoshi:haoshi
                                          }
                                      }).then((e)=>{
                                          if(e)wx.showToast({
                                            title: '您已经完成了比赛，获得第'+mingci+"名",
                                          });
                                      })
                                  });
                              })
                          }
                     });
                  })
              }
          })
      }
  })
  },
    click:function(e){

      this.setData({
        category:e.currentTarget.id+""
      });
      
      var that = this;
      that.setData({
          isWeiwancheng:true
      });
      var database = wx.cloud.database();
      database.collection("tb_item").where({
        userid:that.data.userid,
        matchid:that.data.matchid,
        index:that.data.category+""
    }).get().then((a)=>{
      
        if(a.data.length>0){
            that.setData({
                isWeiwancheng:false
            });
           
        }
    })
      console.log("场景下标："+that.data.category);
     
      database.collection("tb_item").where({
        matchid:that.data.matchid,
        index:that.data.category+""
      }).get().then((res)=>{
         that.setData({
           xuanshou:res.data
         });
         for(let i=0;i<that.data.xuanshou.length;i++){
           var time = that.data.xuanshou[i].time;
           var d = time.toLocaleDateString().substring(0,10);
           var t = time.toTimeString().substring(0,8);
           time = d+" "+t;
           that.data.xuanshou[i].time = time;
         }
         that.setData({
           xuanshou:that.data.xuanshou
         });
      })
    },
    dianji(){
      var k = this.data.category;
      var img =this.data.imageList[k];
      this.setData({
        dialogShow_match:true,
        currentImage:img
      });
    },
    /**
     * 页面的初始数据
     */
    data: {
      isWeiwancheng:true,
      xuanshou:[],
      currentImage:null,
      username:null,
      userid:null,
      matchid:null,
      matchname:null,
      picnames:[],
      imageList:[],
      xuanshou:[],
      matches:match.list,
      category:0,
      id:null,
      dialogShow_match:false 
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
      var that = this;
       wx.getStorage({
         key:"userid",
         success(res){
            that.setData({
              userid:res.data
            });
            //到数据库里面找到当前用户参加的比赛
            var database = wx.cloud.database();
            database.collection("tb_user").where({
              _id:that.data.userid
            }).get().then((r)=>{
              that.setData({
                username:r.data[0].name
              });
            })
            //调用云函数实现多表联合查询
            wx.cloud.callFunction({
                name:"get_current_match",
                data:{
                    userid:that.data.userid
                },
                success:res=>{
                   console.log("云函数返回的数据的条数："+res.result.list.length);
                   var data = res.result.list;
                   for(let i=0;i<data.length;i++){
                       var f1 = true;
                       f1 = data[i].list1[0].hasOwnProperty("beginTime");
                       if(!f1)continue;
                       var f2 = true;
                       for(let j=0;j<data[i].list2.length;j++){
                           if(data[i].matchid == data[i].list2[j].matchid){
                               f2 = false;
                               break;
                           }
                       }
                       if(!f2)continue;
                       console.log("符合条件的比赛下标:"+i);
                       that.setData({
                          matchid:data[i].matchid,
                          matchname:data[i].matchname
                       });
                      
                       break;
                   }
                   wx.setNavigationBarTitle({
                    title: that.data.matchname
                  });
                  database.collection('tb_item').where({
                    matchid:that.data.matchid,
                    index:0+"" 
                  }).get().then((g)=>{
                   
                    that.setData({
                      xuanshou:g.data
                    });
                    //把选手数组当中的时间字段变成可以理解的内容
                    for(let i=0;i<that.data.xuanshou.length;i++){
                      var time = that.data.xuanshou[i].time;
                      var d = time.toLocaleDateString().substring(0,10);
                      var t = time.toTimeString().substring(0,8);
                      var time = d+" "+t;
                      that.data.xuanshou[i].time = time;
                    }
                    that.setData({
                      xuanshou:that.data.xuanshou
                    });
                  });
                  database.collection("tb_match").where({
                    _id:that.data.matchid
                  }).get().then((m)=>{
                    var imageList = m.data[0].imageList;
                    var picnames = [];
                    for(let i=0;i<imageList.length;i++){
                         var data = imageList[i];
                         var loc = data.lastIndexOf("/");
                         data = data.slice(loc+1);
                         loc = data.lastIndexOf(".");
                         data =  data.slice(0,loc);
                         picnames.push(data);
                    }
                    that.setData({
                      imageList:imageList,
                      picnames:picnames
                    });
                    //观察指定比赛、指定分项、指定用户的成绩是否存在
                   
                    database.collection("tb_item").where({
                        userid:that.data.userid,
                        matchid:that.data.matchid,
                        index:0+""
                    }).get().then((a)=>{
                      
                        if(a.data.length>0){
                            that.setData({
                                isWeiwancheng:false
                            });
                           
                        }
                    })
                  });
                }, 
                fail:err=>{ 
                    console.log(err);
                }
            });
          /* database.collection("tb_baoming").aggregate().lookup({
                from:"tb_match",
                localField:"matchid",
                foreignField:"_id",
                as:"matchdetail"
            }).lookup({
                from:"tb_final",
                localField:"userid",
                foreignField:"userid",
                as:"finaldetail"
            }).match({
              userid:that.data.userid,
              _openid:wx.cloud.openid
            }).end().then((msg)=>{
                //判断该比赛必须有开始比赛时间字段而且必须该用户没有完成
               var k = -1;
               for(let i=0;i<msg.data.length;i++){
                   var data = msg.data[i];
                   var f1 =  data.matchdetail[0].hasOwnProperty("beginTime")
                   if(!f1)continue;
                   var f2 = true;
                   for(let j=0;j<data.finaldetail.length;j++){
                       if(data.finaldetail[j].matchid == data.matchid){
                           f2= false;
                           break;
                       }
                   }
                   if(!f2)continue;
                   k = i;

               }
               if(k==-1)return;
              that.setData({
                matchid:msg.data[k].matchid,
                matchname:msg.data[k].matchname
              });
              wx.setNavigationBarTitle({
                title: msg.data[k].matchname,
              });
              database.collection('tb_item').where({
                matchid:that.data.matchid,
                index:0+"" 
              }).get().then((g)=>{
               
                that.setData({
                  xuanshou:g.data
                });
                //把选手数组当中的时间字段变成可以理解的内容
                for(let i=0;i<that.data.xuanshou.length;i++){
                  var time = that.data.xuanshou[i].time;
                  var d = time.toLocaleDateString().substring(0,10);
                  var t = time.toTimeString().substring(0,8);
                  var time = d+" "+t;
                  that.data.xuanshou[i].time = time;
                }
                that.setData({
                  xuanshou:that.data.xuanshou
                });
              });
              database.collection("tb_match").where({
                _id:that.data.matchid
              }).get().then((m)=>{
                var imageList = m.data[0].imageList;
                var picnames = [];
                for(let i=0;i<imageList.length;i++){
                     var data = imageList[i];
                     var loc = data.lastIndexOf("/");
                     data = data.slice(loc+1);
                     loc = data.lastIndexOf(".");
                     data =  data.slice(0,loc);
                     picnames.push(data);
                }
                that.setData({
                  imageList:imageList,
                  picnames:picnames
                });
                //观察指定比赛、指定分项、指定用户的成绩是否存在
               
                database.collection("tb_item").where({
                    userid:that.data.userid,
                    matchid:that.data.matchid,
                    index:0+""
                }).get().then((a)=>{
                  
                    if(a.data.length>0){
                        that.setData({
                            isWeiwancheng:false
                        });
                       
                    }
                })
              });
            })*/
         }
       })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})